package cn.e3.order.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.e3.jedis.JedisClient;
import cn.e3.mapper.TbOrderItemMapper;
import cn.e3.mapper.TbOrderMapper;
import cn.e3.mapper.TbOrderShippingMapper;
import cn.e3.order.pojo.TbOrderInfo;
import cn.e3.order.service.OrderService;
import cn.e3.pojo.TbOrderItem;
import cn.e3.pojo.TbOrderShipping;
import cn.e3.utils.E3Result;
/*
 * 订单服务
 */
@Service
public class OrderServiceImpl implements OrderService{
	@Autowired
	private TbOrderMapper orderMapper;
	@Autowired
	private TbOrderItemMapper orderItemMapper;
	@Autowired
	private TbOrderShippingMapper shippingMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${ORDER_ID_GEN_KEY}")
	private String ORDER_ID_GEN_KEY;
	@Value("${ORDER_ID_START}")
	private String ORDER_ID_START;
	@Value("${ORDER_DETAIL_ID_GEN}")
	private String ORDER_DETAIL_ID_GEN;
	public E3Result createOrder(TbOrderInfo orderInfo) {
		//设置订单号，使用redis完成
		//设置订单id初始值
		if(!jedisClient.exists(ORDER_ID_GEN_KEY)){
			//设置初始值
			jedisClient.set(ORDER_ID_GEN_KEY, ORDER_ID_START);
		}
		//设置订单号，执行一次加一
		String orderId=jedisClient.incr(ORDER_ID_GEN_KEY)+"";
		orderInfo.setOrderId(orderId);
		//1 已付款  2 未付款 3 未发货 .....
		orderInfo.setStatus(1);
		orderInfo.setCreateTime(new Date());
		orderInfo.setUpdateTime(new Date());
		//插入数据表
		orderMapper.insert(orderInfo);
		//更新订单明细表
		//得到订单明细内容
		List<TbOrderItem> orderItems = orderInfo.getOrderItems();
		//遍历明细内人，更新内容，插入数据库
		for (TbOrderItem tbOrderItem : orderItems) {
			//生成id,默认值为1，每次执行向上加一
			Long incr = jedisClient.incr(ORDER_DETAIL_ID_GEN);
			//生成订单号
			tbOrderItem.setId(incr+"");
			//设置订单号
			tbOrderItem.setOrderId(orderId);
			//更新数据库
			orderItemMapper.insert(tbOrderItem);
		}
		//向订单物流表插入数据
		TbOrderShipping shipping = orderInfo.getOrderShipping();
		//补全物流信息
		shipping.setOrderId(orderId);
		shipping.setCreated(new Date());
		shipping.setUpdated(new Date());
		//更新数据库
		shippingMapper.insert(shipping);
		return E3Result.ok(orderId);
	}

}
